from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent
from langchain_core.tools import tool

from common.ali_qwen import get_model

# 初始化语言模型
model = get_model()

# 定义一个简单的工具来获取天气信息
@tool
def get_weather(city: str):
    """Use this tool to get the weather information for a city."""
    if city.lower() in ["上海", "北京"]:
        return f"{city}天气很好"
    elif city.lower() in ["广州", "深圳"]:
        return f"{city}天气糟糕"
    else:
        return "请查看中国天气网"

tools = [get_weather]
memory = MemorySaver()

# 创建启用人机环路的 ReAct 智能体 - 在工具调用前中断
graph_hitl = create_react_agent(model, tools=tools, interrupt_before=["tools"], checkpointer=memory)
# 首次交互 - 智能体将在工具调用之前暂停
config_hitl = {"configurable": {"thread_id": "user_thread_hitl"}}
inputs_hitl = {"messages": [("user", "北京的天气如何？")]}

print("执行智能体（将在工具调用前暂停）...")
stream = graph_hitl.stream(inputs_hitl, config=config_hitl, stream_mode="values")
for output in stream:
    if 'messages' in output and output['messages']:
        last_message = output['messages'][-1]
        print(f"消息类型: {type(last_message).__name__}")
        if hasattr(last_message, 'tool_calls') and last_message.tool_calls:
            print(f"计划调用工具: {last_message.tool_calls}")
            print(">>> 智能体已暂停，等待人工审核 <<<")
            break
        else:
            print(f"内容: {last_message.content}")

# 检查当前状态
print("\n当前智能体状态:")
current_state = graph_hitl.get_state(config_hitl)
print(f"下一个节点: {current_state.next}")
print(f"消息数量: {len(current_state.values['messages'])}")